import { getFileSize } from '../../helper';
import { lookup } from 'mime-types';
import crypto from 'crypto';
import fs from 'node:fs';
import { v4 as uuidv4 } from 'uuid';

export class File {

  constructor(path) {
    this.path = path;
    this.uuid = uuidv4();
  }

  get cdnFileType() {
    const mimeType = lookup(this.path) || '';

    if (mimeType.startsWith('video/')) {
      return 'videoFileType';
    } else if (mimeType.startsWith('image/')) {
      return 'pictureFileType';
    }

    return '';
  }

  get basename() {
    return this.path.split('/').pop();
  }

  getFileSize() {
    return getFileSize(this.path);
  }

  getMd5() {
    return new Promise((resolve, reject) => {
      const hash = crypto.createHash('md5');
      const stream = fs.createReadStream(this.path);
      
      stream.on('data', data => hash.update(data));
      stream.on('end', () => resolve(hash.digest('hex')));
      stream.on('error', error => reject(error));
    });
  }
}